﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Windows.Forms;

namespace TutorialFileCopy {

	class Program {
		[STAThread]
		static void Main(string[] args) {
			if (MessageBox.Show("Should the frameworks rebuilded", "Build frameworks", MessageBoxButtons.YesNo) == DialogResult.No) {
				return;
			}
			//string vsPath = string.Empty;
			//try {
			//    vsPath = Microsoft.Win32.Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\9.0", "InstallDir", String.Empty).ToString();
			//}
			//catch { }
			//if (string.IsNullOrEmpty(vsPath)) {
			//    Console.WriteLine("please install vs 2008");
			//    return;
			//}

			string solutionToBuild = args[0];
			string configurationToBuild = args[1];
			string targetdictionary = args[2];
			string binaryOutputPath = args[3];


			// build solution
			//ProcessStartInfo info = new ProcessStartInfo(vsPath + "\\devenv.com", solutionToBuild + " /build " + configurationToBuild);
			var sys = Environment.GetEnvironmentVariable("windir");
			var exe = sys + @"\Microsoft.NET\Framework\v3.5\MSBuild.exe";
			//System.Windows.Forms.Clipboard.SetText(exe + " " + solutionToBuild);
			//System.Windows.Forms.MessageBox.Show(exe + " " + solutionToBuild);
			ProcessStartInfo info = new ProcessStartInfo(exe, solutionToBuild);
			//info.UseShellExecute = false;
			info.WindowStyle = ProcessWindowStyle.Normal;
			//info.RedirectStandardOutput = true;
			var p = System.Diagnostics.Process.Start(info);
			Console.WriteLine("Compiling frameworks...Please wait about 5 to 10 minutes");
			p.WaitForExit();
			Console.WriteLine("Frameworks are compiled. start copy files");
			p.Close();
			p.Dispose();

			p = null;
			info = null;
			GC.Collect();
			GC.Collect();
			System.Threading.Thread.Sleep(1000);
			string[] c = System.IO.Directory.GetFiles(binaryOutputPath);
			foreach (var file in c) {
				var fileInfo = new System.IO.FileInfo(file);
				var fname = fileInfo.Name;
				if (fname.Contains(".dll")) {
					try {
						System.Console.WriteLine("copy: " + file + " to " + binaryOutputPath);
						fileInfo.CopyTo(targetdictionary + "\\" + fname, true);
					} catch (Exception ex) {
						Console.WriteLine(ex.Message);
					}
				}
			}
		}
	}
}
